package com.zhang.hadoop.flink.test1;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author zhang yufei
 * @date 2022/4/20 6:02 下午
 **/
public class MessageCount {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> lineDataStreamSource = env.readTextFile("flink/input/text01.txt");
        SingleOutputStreamOperator<Tuple3<String, Long, Long>> wordAndOneTuple = lineDataStreamSource.flatMap((String line, Collector<Tuple3<String, Long, Long>> out) -> {
            String[] words = line.split("\t");
            Long num = 0L;
            for (int i = 1; i < words.length; i++) {
                if (words[i].contains("万")) {
                    Float f1 = Float.parseFloat(words[i].substring(0, words[i].length() - 1))*10000;
                    num = f1.longValue();
                } else {
                    num = num + Long.parseLong(words[i]);
                }
            }
            Long count = num;
            if (num == 0L) {
                num = 2L;
            } else {
                num = num / (50000) * 2;
                if (num == 0L) {
                    num = 2L;
                }
            }
            Tuple3 tuple2 = new Tuple3(words[0], num, count);
            out.collect(tuple2);
        }).returns(Types.TUPLE(Types.STRING, Types.LONG, Types.LONG));
        KeyedStream<Tuple3<String, Long, Long>, String> wordAndOneKeyedStream = wordAndOneTuple.keyBy(data -> data.f0);
        SingleOutputStreamOperator<Tuple3<String, Long, Long>> sum = wordAndOneKeyedStream.sum(1);
        sum.print();
        env.execute();
    }
}
